package cn.loan.interceptor;

import cn.loan.config.key.SessionKey;
import cn.loan.entity.User;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 毛苏宇
 * @Description: You can do it!
 * @Date: Create in 9:57 2019/3/20
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String host = request.getRemoteHost();  //得到IP地址
        String url = request.getRequestURI();   //得到访问的URL
        HttpSession session = request.getSession();     //得到session对象
        //判断是否是静态文件
/*        if (url.contains("static")) {
            System.out.println("访问的是静态文件,放行");
            return true;
        }*/

        //放行部分页面
        for (String uri : releaseLink()) {
            if (url.contains(uri)) {
                return true;
            }
        }
        //如果不是这些页面,那么就开始判断用户是否已经登录
        User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        //如果已经登录就放行
        if (null != user) {
            return true;
        } else {
            //未登录,直接跳转至登录页面
            response.sendRedirect("/loan/user/login");
        }
        return false;
    }


    /**
     * 可被放行的url
     *
     * @return
     */
    private List<String> releaseLink() {
        List<String> url = new ArrayList<String>();
        url.add("login");
        url.add("register");
        url.add("retrieve");
        url.add("sendModifyPwdMsg");
        url.add("sendRegisterMsg");
        url.add("api");
        return url;
    }

}
